import { Injectable, Injector } from '@angular/core';
import { Observable, of, Subject } from 'rxjs';
import { FormBasicService, FarrisMetadataService, FarrisMetadataDto, DesignerEnvType } from '@farris/designer-services';
import { HttpClient } from '@angular/common/http';
import { omit } from 'lodash-es';
import { delay } from 'rxjs/operators';

/**
* 开源环境通用的获取元数据、保存元数据的服务
*/
@Injectable()
export class DesignerMetadataService implements FarrisMetadataService {

    constructor(private http: HttpClient, private injector: Injector) { }

    getMetadata(metadataId: string): Observable<FarrisMetadataDto> {
        return this.http.get<FarrisMetadataDto>(`assets/metadata/${metadataId}.json`);
    }

    // saveMetadata(metadataDto: FarrisMetadataDto): Observable<any> {
    //     const sessionId = '';

    //     return this.metadataServ.SaveMetadata(metadataDto, sessionId);
    // }

    getFormMetadata(): Observable<FarrisMetadataDto> {
        const subject = new Subject<any>();
        const formBasicServ = this.injector.get(FormBasicService);
        formBasicServ.envType = DesignerEnvType.designer;
        const metadataId = this.getQueryVariable('metadataId');
        this.http.get(`assets/metadata/${metadataId}.json`).subscribe((data: FarrisMetadataDto) => {
            formBasicServ.formMetaBasicInfo = omit(data, 'content') as FarrisMetadataDto;

            // 兼容Contents 为string和object两种类型的表单
            let domJson = JSON.parse(data.content).Contents;
            if (typeof (domJson) === 'string') {
                domJson = JSON.parse(domJson);
            }
            subject.next(domJson);
        });

        return subject;

    }

    getMetadataList(typeName: string): Observable<any> {
        // const relativePath = this.formBasicServ.formMetaBasicInfo.relativePath;
        // return this.metadataService.getMetadataList(relativePath, typeName);
        // const subject = new Subject<any>();

        // subject.de

        return of([]).pipe(delay(300));
    }

    // validateRepeatName(relativePath: string, fileName: string): Subject<any> {
    //     return this.metadataService.ValidateRepeatName(relativePath, fileName);
    // }

    /**
     * 获取url参数
     * @param variable 参数编号
     */
    private getQueryVariable(variable) {

        const query = window.location.href.substring(window.location.href.indexOf('?') + 1);
        const vars = query.split('&');
        let targetVariable;
        vars.some(v => {
            const pair = v.split('=');
            if (pair[0] === variable) { targetVariable = pair[1]; return true; }
        });

        return targetVariable;
    }
}
